import { toast, Toaster } from 'sonner';
import { useSettingsStore, Status } from '@/store';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import { getCurrentTab } from '@/lib/utils';
import { MessageType } from '@/config';

function Settings() {
  const dispatch = useSettingsStore((state) => state.dispatch);
  const status = useSettingsStore((state) => state.status);
  function running() {
    dispatch({
      type: 'update',
      update(draftState) {
        draftState.status = Status.RUNNING;
      },
    });
    toast.success('启动', {
      position: 'bottom-right',
    });
  }

  function stop() {
    dispatch({
      type: 'update',
      update(draftState) {
        draftState.status = Status.STOP;
      },
    });
    toast.success('暂停', {
      position: 'bottom-right',
    });
  }

  function onCheckedChange(checked: boolean | 'indeterminate') {
    if (checked) {
      running();
    } else {
      stop();
    }
  }

  async function openOperationInstruction() {
    const currentTab = await getCurrentTab();
    if (currentTab && currentTab.id) {
      browser.tabs.sendMessage(currentTab.id, {
        type: MessageType.openOperationInstruction,
      });
    }
  }

  async function clearSettings() {
    await browser.storage.local.clear();
    toast.success('已清空所有配置', {
      position: 'bottom-right',
    });
  }

  async function exportSettings() {
    const settings = await browser.storage.local.get(null);
    const settingsString = JSON.stringify(settings);
    // 使用 ShowSaveFilePickerOptions 导出
    const fileHander = await window.showSaveFilePicker({
      suggestedName: 'settings.json',
      types: [
        {
          description: 'JSON 文件',
          accept: {
            'application/json': ['.json'],
          },
        },
      ],
    });
    const file = await fileHander.createWritable();
    await file.write(settingsString);
    await file.close();
    toast.success('导出成功');
  }

  async function importSettings() {
    const fileHander = await window.showOpenFilePicker();
    const file = await fileHander[0].getFile();
    const settingsString = await file.text();
    await browser.storage.local.set(JSON.parse(settingsString));
    toast.success('导入成功');
  }

  return (
    <>
      {/* <div className="flex items-center space-x-2">
        <Switch
          checked={status === Status.RUNNING}
          onCheckedChange={onCheckedChange}
          id="airplane-mode"
        />
        <Label htmlFor="airplane-mode">
          <span className={`${status === Status.RUNNING ? 'text-primary' : ''}`}>启动</span>/
          <span className={`${status === Status.STOP ? 'text-[red]' : ''}`}>暂停</span>
        </Label>
      </div> */}
      <div className="relative">
        <div className="flex items-center gap-2">
          <Button size={'sm'} onClick={exportSettings}>
            导出配置
          </Button>
          <Button size={'sm'} onClick={importSettings}>
            导入配置
          </Button>
          <Button variant={'destructive'} size={'sm'} onClick={clearSettings}>
            重置配置
          </Button>
        </div>
        <Button
          onClick={openOperationInstruction}
          className="absolute right-7 top-1 bg-transparent hover:bg-transparent p-0 text-cyan-600 h-auto hover:underline hover:text-cyan-600/90"
        >
          使用说明
        </Button>
      </div>
    </>
  );
}

export function ExtensionSettings(props: React.ButtonHTMLAttributes<HTMLDivElement>) {
  return (
    <div {...props}>
      <div className="flex flex-col min-h-[200px]">
        <div className="flex-1">
          <Settings></Settings>
        </div>
        <Toaster duration={2000} className="max-w-[150px] !left-auto !right-0"></Toaster>
      </div>
    </div>
  );
}
